package com.qingcloud.base.pojo;

import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Getter
@Setter
@NoArgsConstructor
public class Result<T> implements Serializable {


    public static <T> Result<T> success(T object) {
        return  of(object, SUCCEED_CODE,"");
    }
    public static <T> Result<T> success() {
        return of(null, SUCCEED_CODE, "");
    }
    public static <T> Result<T> of(T object, Integer code, String msg) {
        return new Result<>(code, msg, object, "");
    }

    public static <T> Result<T> fail(String message) {
        return of(null, FAIL_CODE, "");
    }

    public static <T> Result<T> fail(String message, String trace) {
        return new Result<T>(FAIL_CODE, message, null, trace);
    }

    public static <T> Result<T> fail(int code, String message, String trace) {
        return new Result<T>(code, message, null, trace);
    }

    public Result(Integer errorCode, String errorMessage, T result, String trace) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss");
        this.code = errorCode;
        this.error = errorMessage;
        this.result = result;
        this.trace = trace;
        this.setTimes(dateTimeFormatter.format(LocalDateTime.now()));
    }

    public static final Integer SUCCEED_CODE = 2000;

    public static final Integer FAIL_CODE = 505;

    @ApiModelProperty(value = "返回码 0成功 其他错误", example = "0")
    protected int code;

    @ApiModelProperty(value = "错误信息，成功时为空", example = "网络错误")
    protected String error;

    @ApiModelProperty(value = "抛出异常时的堆栈信息", example = "throw Exception")
    protected String trace;

    @ApiModelProperty(value = "AJAX结果数据", example = "网络错误")
    private T result;

    @ApiModelProperty(value = "结果是否成功")
    private boolean successful;

    /**
     * 处理完成时间
     */
    @ApiModelProperty(value = "处理完成时间")
    private String times;

    /**
     * 检查api结果是否成功
     */
    public boolean isSuccessful() {
        return SUCCEED_CODE.equals(this.code);
    }

}
